package main

import (
	"github.com/spf13/cast"
	"fmt"
	"html/template"
	"net/http"
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
)
 
// 定义返回json结构体
type JsonResult struct {
	Errcode int
	Errmsg  string
	Result  interface{}
}
 
// JsonResult 设置默认值
func newJsonResult() *JsonResult {
	return &JsonResult{Errcode: 0, Errmsg: "sccess"}
}
 
func main() {
	http.HandleFunc("/wx", getToken)

	http.HandleFunc("/testGet", testGet)
	http.HandleFunc("/testPost", testPost)
	http.HandleFunc("/testPostJson", testPostJson)

	http.HandleFunc("/", webfun)
	http.HandleFunc("/name", name)
	fmt.Println("服务启动")
	err := http.ListenAndServe(":90", nil)

	if err != nil {
		fmt.Println("服务器开启错误：", err)
	}
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func getToken(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
 
	// 第一种方法
	//name := query["name"][0]
 
	// 第二种方法
	// name := query.Get("name")

	var appid string = "wx7287a60bb700fd21";
  var secret string = "1ef8755f92bebae8ad7bab432ba29cbf";

	// 获取前端传过来的code
	// var code string = param["code"].(string)
	fmt.Println(query)
	var code string  = query.Get("code")
	fmt.Println("code:"+code)
	tokenUrl := "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code"
	// res,_ :=http.Get("https://www.baidu.com/")
	res,_ :=http.Get(tokenUrl)
	defer res.Body.Close()
	thebody,_ := ioutil.ReadAll(res.Body)
	fmt.Print(cast.ToString(thebody))
	var strBody string = cast.ToString(thebody)

	var tempMap map[string]interface{}
	json.Unmarshal([]byte(strBody), &tempMap)
	fmt.Println(tempMap)
	fmt.Println("access_token:"+tempMap["access_token"].(string))

	access_token := tempMap["access_token"].(string);
	openid       := tempMap["openid"].(string);

	// 2.获取用户信息 有不懂的，可以微信我号yizheng369
	user_url := "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
	resp,_ :=http.Get(user_url)
	defer resp.Body.Close()
	userbody,_ := ioutil.ReadAll(resp.Body)

	io.WriteString(w, string(userbody))
}
 
//  接受application/json类型的post请求
func testPostJson(w http.ResponseWriter, r *http.Request) {
	var param map[string]interface{}
	body, _ := ioutil.ReadAll(r.Body)
	json.Unmarshal(body, &param)
 
	result := make(map[string]interface{})
	result["params"] = param["username"]
 
	jsonResult := new(JsonResult)
	jsonResult.Errcode = 200
	jsonResult.Errmsg = "success"
	jsonResult.Result = result
 
	msg, _ := json.Marshal(jsonResult)
 
	io.WriteString(w, string(msg))
}
 
// 接受x-www-form-urlencoded类型的post请求
func testPost(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
 
	// 第一种
	//name := r.Form["username"][0]
	//passwd := r.Form["passwd"][0]
 
	// 第二种
	name := r.Form.Get("username")
	passwd := r.Form.Get("passwd")
 
	result := make(map[string]string)
	result["name"] = name
	result["passwd"] = passwd
 
	jsonResult := new(JsonResult)
	jsonResult.Errcode = 200
	jsonResult.Errmsg = "success"
	jsonResult.Result = result
 
	msg, _ := json.Marshal(jsonResult)
 
	io.WriteString(w, string(msg))
}
 
// 接收get参数
func testGet(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
 
	// 第一种方法
	//name := query["name"][0]
 
	// 第二种方法
	name := query.Get("name")
 
	result := make(map[string]string)
	result["name"] = name
 
	jsonResult := newJsonResult()
 
	jsonResult.Result = result
 
	msg, _ := json.Marshal(jsonResult)
 
	io.WriteString(w, string(msg))
}
// 原文链接：https://blog.csdn.net/lonely_fool/article/details/119423485

func webfun(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Fprintln(w, "开启go web")
	for k, v := range r.URL.Query() {
		fmt.Println("key:", k, ", value:", v[0])
	}
	for k, v := range r.PostForm {
		fmt.Println("key:", k, ", value:", v[0])
	}

}

func name(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("./templates/index.html")
	data := map[string]string{
		"name": "data2",
		"name3": "data3",
	}
	t.Execute(w, data)
}
